package com.fast.bigdata.hourglass.util;

import akka.actor.ActorSelection;
import akka.actor.ActorSystem;
import akka.pattern.Patterns;
import akka.util.Timeout;
import bigdata.hourglass.common.domain.Bean;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import scala.concurrent.Await;
import scala.concurrent.Future;
import scala.concurrent.duration.Duration;

/**
 * @author leo.jie (weixiao.me@aliyun.com)
 * @version 1.0
 * @organization CC
 * @website https://www.jlpyyf.com
 * @date 2019/12/8 10:25 下午
 * @since 1.0
 */
@Component
public class ActorUtil {
    @Autowired
    private ActorSystem actorSystem;

    public JSONObject queryActor(String actorAddress, String actorName, Object bean) {
        JSONObject resultObj = new JSONObject();
        ActorSelection selection = actorSystem.actorSelection("akka.tcp://HourglassEngineSystem@" +
                actorAddress + "/user/" + actorName);
        try {
            Timeout timeout = new Timeout(Duration.create(10, "s"));
            Future<Object> future = Patterns.ask(selection, bean, timeout);
            Object obj = Await.result(future, timeout.duration());
            String resultStr;
            resultObj.put("isSuccess", true);
            if (obj instanceof Bean.HourglassExecution) {
                Bean.HourglassExecution result1 = (Bean.HourglassExecution) obj;
                return result1.toJSONObject();
            } else {
                resultStr = obj.toString();
            }
            resultObj.put("data", resultStr);
        } catch (Exception e) {
            resultObj.put("data", e.getMessage());
            resultObj.put("isSuccess", false);
        }
        return resultObj;
    }

}
